const API_BASE = '/products';




// window.onload=()=>showView()

window.onload=requestProductsAndShow


async function requestProductsAndShow(){
    try{
        const resp=await  fetch(API_BASE)
        if (!resp.ok)  throw new Error(`HTTP错误! 状态码: ${resp.status}`)
        const  data =await resp.json()
        renderProducts(data.products)
    }catch (error){
        console.log(error)
        throw error
    }
}
// 显示/隐藏视图
function showView(viewName) {
    console.log("function showView(viewName) {")
    document.querySelectorAll('.view').forEach(view => {
        view.style.display = 'none';
    });
    document.getElementById(`${viewName}-view`).style.display = 'block';

    if (viewName === 'list') {
        loadProducts();
    }
}
// 加载产品列表
async function loadProducts() {

    console.log("async function loadProducts()")
    try {
        const response = await fetch(API_BASE);
        if (!response.ok) throw new Error("刷新 商品失败")
        const result = await response.json();
        if (result.success) {
            renderProducts(result.products);
        } else {
            showAlert('加载产品失败', 'danger');
        }
    } catch (error) {
        showAlert('网络错误: ' + error.message, 'danger');
    }
}
// 渲染产品表格
function renderProducts(products) {
    const tbody = document.getElementById('products-table');
    tbody.innerHTML = '';
    products.forEach(product => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${product.id}</td>
            <td>${product.name}</td>
            <td>${product.model || '-'}</td>
            <td>${product.brand || '-'}</td>
            <td>¥${product.purchase_price || '0.00'}</td>
            <td>¥${product.retail_price || '0.00'}</td>
            <td>${product.min_stock || 0}-${product.max_stock || 0}</td>
            <td>
                <button class="btn btn-sm btn-warning" onclick="editProduct(${product.id})">
                    编辑
                </button>
                <button class="btn btn-sm btn-danger" onclick="deleteProduct(${product.id})">
                    删除
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
}
// 创建产品
document.getElementById('product-form').addEventListener('submit', async (e) => {
    e.preventDefault();

    const formData = new FormData(e.target);
    const product = Object.fromEntries(formData.entries());
    // 转换数字字段
    product.category_id = parseInt(product.category_id) || 0;
    product.purchase_price = parseFloat(product.purchase_price) || 0;
    product.retail_price = parseFloat(product.retail_price) || 0;
    product.min_stock = parseInt(product.min_stock) || 0;
    product.max_stock = parseInt(product.max_stock) || 0;
    try {
        const response = await fetch(API_BASE, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(product),
        });
        const result = await response.json();

        if (result.success) {
            showAlert('产品创建成功', 'success');
            e.target.reset();
            showView('list');
        } else {
            showAlert('创建失败: ' + result.message, 'danger');
        }
    } catch (error) {
        showAlert('网络错误: ' + error.message, 'danger');
    }
});
// 编辑产品
async function editProduct(id) {
    try {
        const response = await fetch(`${API_BASE}/${id}`);
        const result = await response.json();
        if (result.success) {
            // 填充编辑表单
            const product = result.product;
            const form = document.getElementById('edit-form');
            Object.keys(product).forEach(key => {
                const input = form.querySelector(`[name="${key}"]`);
                if (input) input.value = product[key] || '';
            });

            showView('edit');
        }
    } catch (error) {
        showAlert('加载产品详情失败', 'danger');
    }
}
// 删除产品
async function deleteProduct(id) {
    if (!confirm('确定要删除这个产品吗？')) return;

    try {
        const response = await fetch(`${API_BASE}/${id}`, {
            method: 'DELETE',
        });
        const result = await response.json();
        if (result.success) {
            showAlert('产品删除成功', 'success');
            loadProducts();
        } else {
            showAlert('删除失败: ' + result.message, 'danger');
        }
    } catch (error) {
        showAlert('网络错误: ' + error.message, 'danger');
    }
}

// 显示提示消息
function showAlert(message, type) {
    const alert = document.createElement('div');
    alert.className = `alert alert-${type} alert-dismissible fade show`;
    alert.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(alert);
    setTimeout(() => {
        alert.remove();
    }, 3000);
}

// 初始化加载产品列表
document.addEventListener('DOMContentLoaded', () => {
    loadProducts();
});